package com.applink.sell_proof;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.database.table.ProductImageDBHelper;
import com.applink.sell_proof.model.MyImage;
import com.applink.sell_proof.model.ProductImage;
import com.applink.sell_proof.urlimageviewhelper.GalleryViewPager;
import com.applink.sell_proof.urlimageviewhelper.UrlPagerAdapter;
import com.applink.sell_proof.util.Utility;

public class ProductActivity extends BaseActionBarActivity implements
		OnItemSelectedListener {
	private Context mContext;
	private GalleryViewPager galleryProductImage;
	private ImageView imgNoPromotion;
	private ArrayList<MyImage> mUrlProductImage = new ArrayList<MyImage>();
	private ArrayList<ProductImage> mDataSelect = new ArrayList<ProductImage>();
	private ProgressDialog processDialog;
	private static final int SHOW_PRODUCT_IMAGE = 0;
	private static final int SHOW_PROGRESS = 1;
	private static final int DISMISS_PROGRESS = 2;
	private boolean checkLoadFirst = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.price_book);
		checkLoadFirst = true;
		mContext = this;
		processDialog = new ProgressDialog(this);
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		int checkState = Utility.checkTimeValidation();
		switch (checkState) {
		case 0:
			Utility.showAlertDialogLogout(this,
					android.R.drawable.ic_dialog_alert,
					Utility.messageServerTimeOut, Utility.titleServerTimeOut,
					ProductActivity.this);
			break;
		case 1:
			Utility.showAlertDialogLogout(this,
					android.R.drawable.ic_dialog_alert,
					Utility.messageLocalTimeOut, Utility.titleLocalTimeOut,
					ProductActivity.this);
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.get_lastest_product_image, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_get_lastest_product_image:
			showloading();
			new AsyncTask<Void, Void, Integer>() {
				@Override
				protected Integer doInBackground(Void... params) {
					Utility.checkGetLastestProduct = true;
					mHandler.sendEmptyMessage(SHOW_PROGRESS);
					// ProductImageDBHelper.deleteProductImage();
					DataHelper.getInstance().getProductImage();
					hideloading();
					return 0;
				}

				@Override
				protected void onPostExecute(Integer result) {
					mHandler.sendEmptyMessage(DISMISS_PROGRESS);
					super.onPostExecute(result);
					// initView();
					loadData(Utility.mDataProductImage);
					mHandler.sendEmptyMessage(SHOW_PRODUCT_IMAGE);
				}

			}.execute((Void) null);
			break;

		default:
			break;
		}
		return false;
	}

	private void initView() {
		Utility.mDataProductImage = ProductImageDBHelper.getAllProductImage();
		new dowloadPromotion().execute();
		Spinner spin = (Spinner) findViewById(R.id.spinnerPriceBook);
		spin.setOnItemSelectedListener(this);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.product_image,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adapter);

		if (galleryProductImage == null) {
			galleryProductImage = (GalleryViewPager) findViewById(R.id.gallery_price_book);
		}
		if (imgNoPromotion == null) {
			imgNoPromotion = (ImageView) findViewById(R.id.img_no_photo_price_book);
		}
		mHandler.sendEmptyMessage(SHOW_PRODUCT_IMAGE);
	}

	private class dowloadPromotion extends AsyncTask<Void, Void, Integer> {

		@Override
		protected Integer doInBackground(Void... params) {
			if (Utility.mDataProductImage != null
					&& Utility.mDataProductImage.size() > 0) {

				for (int i = 0; i < Utility.mDataProductImage.size(); i++) {
					if (Utility.mDataProductImage.get(i).getLocalPath() != null
							&& Utility.mDataProductImage.get(i).getLocalPath()
									.length() == 0) {
						String url = Utility.download(Utility.mDataProductImage
								.get(i).getPhysicalPath().toString());
						System.out.println(">>>>> " + url);
						if (url != null) {
							Utility.mDataProductImage.get(i).setLocalPath(url);
						}
						mDataSelect.add(Utility.mDataProductImage.get(i));
						ProductImageDBHelper.updateProductImage((mDataSelect
								.get(i)));
					}
				}
			}
			return 0;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parentView, View view,
			int position, long id) {
		checkLoadFirst = false;
		if (position == 0) {
			changeOptionSelect("All");
		} else if (position == 1) {
			changeOptionSelect("desktop");
		} else if (position == 2) {
			changeOptionSelect("notebook");
		}
		new showProductImage().execute();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			switch (arg0.what) {
			case SHOW_PRODUCT_IMAGE:
				if (mUrlProductImage.size() > 0) {
					imgNoPromotion.setVisibility(View.GONE);
					galleryProductImage.setVisibility(View.VISIBLE);
					UrlPagerAdapter pagerAdapter = new UrlPagerAdapter(
							mContext, mUrlProductImage);
					galleryProductImage.setAdapter(pagerAdapter);
				} else {
					imgNoPromotion.setVisibility(View.VISIBLE);
					galleryProductImage.setVisibility(View.GONE);
				}

				break;

			case SHOW_PROGRESS:
				Utility.showWaitingStatus(processDialog);
				break;

			case DISMISS_PROGRESS:
				Utility.hideWaitingStatus(processDialog);
				break;

			default:
				break;
			}
			return false;
		}
	});

	private class showProductImage extends AsyncTask<Void, Void, Integer> {

		@Override
		protected Integer doInBackground(Void... params) {
			// savePriceBook();
			if (checkLoadFirst) {
				loadData(Utility.mDataProductImage);
			} else {
				loadData(mDataSelect);
			}
			hideloading();
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			// getButton_Clicked();
			mHandler.sendEmptyMessage(SHOW_PRODUCT_IMAGE);
		}

	}

	private void loadData(ArrayList<ProductImage> data) {
		mUrlProductImage.clear();
		if (data != null && data.size() > 0) {
			for (int i = 0; i < data.size(); i++) {
				MyImage objectPDFImage = new MyImage();
				if (data.get(i).getLocalPath() != null
						&& data.get(i).getLocalPath().length() > 0) {
					objectPDFImage.setImageLocation(Uri.parse(data.get(i)
							.getLocalPath()));
				} else {
					objectPDFImage.setImageLocation(Uri.parse(data.get(i)
							.getPhysicalPath()));
				}
				mUrlProductImage.add(i, objectPDFImage);
			}
		}
		// for (int i = 0; i < data.size(); i++) {
		// MyImage objectPDFImage = new MyImage();
		// // objectPDFImage.setImageLocation(Uri.parse(getImages()[i]));
		// objectPDFImage.setImageLocation(Uri.parse(data.get(i)
		// .getPhysicalPath()));
		// mUrlPromotion.add(i, objectPDFImage);
		// }
	}

	private void changeOptionSelect(String optionName) {
		mDataSelect.clear();
		if (Utility.mDataProductImage != null) {
			if (optionName.equals("All")) {
				mDataSelect.addAll(Utility.mDataProductImage);
			} else if (Utility.mDataProductImage.size() > 0) {
				for (int i = 0; i < Utility.mDataProductImage.size(); i++) {
					if (optionName.equals(Utility.mDataProductImage.get(i)
							.getSaleCategoryName().toLowerCase())) {
						mDataSelect.add(Utility.mDataProductImage.get(i));
					}
				}
			}
		}
	}

}
